package com.ldj.tim.server.consumer;

import com.ldj.tim.common.constant.MqConstants;
import com.ldj.tim.common.dto.MsgContentDTO;
import com.ldj.tim.common.dto.P2PInfoDTO;
import com.ldj.tim.common.pojo.P2PInfo;
import com.ldj.tim.server.config.IdsTableNameHandler;
import com.ldj.tim.server.mapper.MessageMapper;
import com.ldj.tim.server.mapper.P2PMapper;
import com.ldj.tim.server.util.RabbitMsgUtil;
import com.rabbitmq.client.Channel;
import org.hibernate.validator.internal.constraintvalidators.bv.time.futureorpresent.FutureOrPresentValidatorForReadableInstant;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * @author majinhui
 * @description
 * @create 2024/11/11 17:29
 **/

@Component
@RabbitListener(queues = MqConstants.QUEUE_DURABLE)
public class Msg2DbConsumer {

    @Autowired
    private RabbitMsgUtil rabbitMsgUtil;

    @Autowired
    private P2PMapper p2PMapper;
     @Autowired
    private MessageMapper messageMapper;

    @RabbitHandler
    public void receiveMessage(Message message, P2PInfo info, Channel channel) throws IOException {
        try {
            long deliveryTag = message.getMessageProperties().getDeliveryTag();
            System.out.println("Msg2DbConsumer 消费消息：" + info);
            P2PInfoDTO p2PInfoDTO = new P2PInfoDTO(info);
            MsgContentDTO msgContentDTO = new MsgContentDTO(info);
            IdsTableNameHandler.initData(p2PInfoDTO);
            p2PMapper.insert(p2PInfoDTO);
            messageMapper.insert(msgContentDTO);
            channel.basicAck(deliveryTag,false);
        } catch (Exception e) {
            rabbitMsgUtil.retryMessage(message, info, channel, MqConstants.DLX_DURABLE_ROUTING_KEY);
        }

    }


}
